package com.jzwl.common.qiniu;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.google.common.io.ByteStreams;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

/**
 * 图片/文件上传，使用七牛云服务
 * <p>
 * @author   朱晓川
 * @Date	 2017年11月20日
 */
@Component
public class QiniuUploadService {

	protected Logger logger = LoggerFactory.getLogger(QiniuUploadService.class);

	private static final String IMAGE_BUCKET = "image-open-plat";
	private static final String FILE_BUCKET = "file-open-plat";

	private Auth auth = Auth.create(QiniuAkConfig.ACCESS_KEY, QiniuAkConfig.SECRET_KEY);

	// 重用 uploadManager。一般地，只需要创建一个 uploadManager 对象
	private static UploadManager uploadManager;

	static {
		Zone zone = Zone.zone1();
		Configuration conf = new Configuration(zone);
		uploadManager = new UploadManager(conf);
	}

	// 简单图片上传，使用默认策略
	private String getImageUpToken() {
		return auth.uploadToken(IMAGE_BUCKET);
	}

	// 简单文件上传
	private String getFileUpToken() {
		return auth.uploadToken(FILE_BUCKET);
	}

	/**
	 * 七牛图片上传，上传到图片bucket
	 */
	public String uploadImage(InputStream inStream, String file_ext_name, String dest_filename) {

		byte[] data = null;
		try {
			data = ByteStreams.toByteArray(inStream);
		} catch (IOException e) {
			e.printStackTrace();
		}
		String upToken = getImageUpToken();
		String fileName = UUID.randomUUID().toString() + "." + file_ext_name;

		DefaultPutRet ret = upload(data, fileName, upToken);
		return ret.key;
	}

	private DefaultPutRet upload(byte[] data, String key, String upToken) {
		DefaultPutRet ret = null;
		try {
			//华北区
			Response res = uploadManager.put(data, key, upToken);

			if (res.isOK()) {
				ret = res.jsonToObject(DefaultPutRet.class);
				return ret;
			} else {
				// 上传失败
				logger.info(res.bodyString());
			}
		} catch (QiniuException e) {
			Response r = e.response;
			// 请求失败时简单状态信息
			logger.error(r.toString());
			try {
				// 响应的文本信息
				logger.error(r.bodyString());
			} catch (QiniuException e1) {
				// ignore
			}
		}
		return ret;
	}

	/**
	 * 七牛文件上传，上传到文件bucket
	 */
	public String uploadFile(InputStream inStream, String file_ext_name, String dest_filename) {

		byte[] data = null;
		try {
			data = ByteStreams.toByteArray(inStream);
		} catch (IOException e) {
			e.printStackTrace();
		}
		String upToken = getFileUpToken();//file
		String fileName = UUID.randomUUID().toString() + "." + file_ext_name;

		DefaultPutRet ret = upload(data, fileName, upToken);
		return ret.key;

	}
}
